$(document).ready(function () {
  // ----------------- 全局数据--------------------
  let pageNum = 1;
  let pageSize = 5;
  let total = 0;
  let tableData = {};

  // -----------------生命周期（立即执行函数） -----------------
  (function created() {
    renderPositionSelect();
    renderRoleSelect();
    loadTableData();
    bindEventListener();
  })();

  // ------------------ 方法 ----------------
  function renderPositionSelect() {
    const selectIds = [
      "#search-form-match-team-id",
      "#modal-form-first-team-id",
      "#modal-form-second-team-id",
    ];
    listTeam().then((response) => {
      if (response.code === 200) {
        const positions = response.data;
        selectIds.forEach((selectId) => {
          $("<option></option>")
            .attr("name", "teamId")
            .attr("value", "")
            .text("Select Team")
            .prop("hidden", true)
            .prop("selected", false)
            .appendTo(selectId);
          $.each(positions, function (index, item) {
            $("<option></option>")
              .attr("name", "teamId")
              .attr("value", item.id)
              .text(item.name)
              .appendTo(selectId);
          });
        });
      }
    });
  }

  function renderRoleSelect() {
    const selectIds = ["#search-form-role", "#modal-form-role"];
    selectIds.forEach((selectId) => {
      listRole().then((response) => {
        if (response.code === 200) {
          let roles = response.data;

          $("<option></option>")
            .attr("name", "roleId")
            .attr("value", "")
            .text("Select Role")
            .prop("hidden", true)
            .prop("selected", false)
            .appendTo(selectId);

          $.each(roles, function (index, role) {
            $("<option></option>")
              .attr("name", "roleId")
              .attr("value", role.id)
              .text(role.name)
              .appendTo(selectId);
          });
        }
      });
    });
  }

  function loadTableData() {
    showLoading(true);
    const body = {
      matchName: $("#search-from-match-name").val() || null,
      matchTime: $("#search-from-match-time").val() || null,
      firstTeamId: $("#search-form-match-team-id").val() || null,
      secondTeamId: $("#search-form-match-team-id").val() || null,
    };

    pageMatch(body, { pageNum, pageSize })
      .then((response) => {
        console.log(response);

        tableData = response.data.records;
        total = response.data.total;
        renderTable();
        renderPagination();
      })
      .catch((error) => {
        console.error(error);
      })
      .finally(() => {
        showLoading(false);
      });
  }

  // 渲染表格
  function renderTable() {
    const $tbody = $("#tbody");
    $tbody.empty();

    if (tableData.length === 0) {
      $tbody.append(`
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted">No matching data found!</td>
                </tr>
            `);
      return;
    }

    tableData.forEach((item) => {
      $tbody.append(`
                <tr>
                    <td>${item.id}</td>
                    <td>
                        <div class="d-flex align-items-center">
                           ${item.matchName}
                        </div>
                    </td>
                    <td>${item.matchTime}</td>
                    <td>${item.firstTeam.name} vs ${item.secondTeam.name}</td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-btn" data-id="${item.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${item.id}">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `);
    });
  }

  // 渲染分页
  function renderPagination() {
    const $pagination = $("#pagination");
    $pagination.empty();

    // 上一页按钮
    $pagination.append(`
            <li class="page-item ${pageNum === 1 ? "disabled" : ""}">
                <a class="page-link" href="#" data-page="${pageNum - 1}">
                    <i class="fas fa-angle-left"></i>
                </a>
            </li>
        `);

    // 页码按钮
    const startPage = Math.max(1, pageNum - 2);
    const endPage = Math.min(Math.ceil(total / pageSize), pageNum + 2);

    for (let i = startPage; i <= endPage; i++) {
      $pagination.append(`
                <li class="page-item ${i === pageNum ? "active" : ""}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `);
    }

    // 下一页按钮
    $pagination.append(`
            <li class="page-item ${
              pageNum === Math.ceil(total / pageSize) ? "disabled" : ""
            }">
                <a class="page-link" href="#" data-page="${pageNum + 1}">
                    <i class="fas fa-angle-right"></i>
                </a>
            </li>
        `);
  }

  // 显示/隐藏加载状态
  function showLoading(show) {
    $("#loading-spinner").toggle(show);
    $(".table-responsive").toggle(!show);
  }

  function bindEventListener() {
    // 搜索按钮点击事件
    $("#search-btn").on("click", function () {
      loadTableData();
    });

    // 重置搜索条件
    $("#reset-btn").on("click", function () {
      $("#search-from-match-name").val("");
      $("#search-form-match-team-id").val("");
      $("#search-form-trainging-time").val("");
      loadTableData();
    });

    // 分页点击事件
    $("#pagination").on("click", ".page-link", function (e) {
      e.preventDefault();
      const page = $(this).data("page");
      if (page >= 1 && page <= Math.ceil(total / pageSize)) {
        pageNum = page;
        loadTableData();
      }
    });

    // 添加用户按钮点击事件
    $("#add-btn").on("click", function () {
      $("#modal-form")[0].reset();
      $("#modal-form-id").val("");
      $("#modal-title").text("添加用户");
      $("#modal").modal("show");
    });

    // 编辑按钮点击事件（委托事件处理）
    const $tbody = $("#tbody");
    $tbody.on("click", ".edit-btn", function () {
      const id = $(this).data("id");
      const $btn = $(this);

      $btn.html('<span class="spinner-border spinner-border-sm"></span>');
      $btn.prop("disabled", true);

      function formatDateTimeForInput(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
      }

      getMatch(id)
        .then((response) => {
          const item = response.data;
          console.log(item);
          
          $("#modal-form-id").val(item.id);
          $("#modal-form-match-name").val(item.matchName);
          $("#modal-form-match-time").val(formatDateTimeForInput(item.matchTime));
          $("#modal-form-first-team-id").val(item.firstTeamId);
          $("#modal-form-second-team-id").val(item.secondTeamId);

          $("#modal-title").text("编辑用户");
          $("#modal").modal("show");

          $("").children();
        })
        .catch((error) => {
          console.error("获取用户信息失败:", error);
          alert("获取用户信息失败");
        })
        .finally(() => {
          $btn.html('<i class="fas fa-edit"></i>');
          $btn.prop("disabled", false);
        });
    });

    // 删除按钮点击事件（委托事件处理）
    $tbody.on("click", ".delete-btn", function () {
      const userId = $(this).data("id");
      const $btn = $(this);

      if (confirm("确定要删除这个用户吗？")) {
        $btn.html('<span class="spinner-border spinner-border-sm"></span>');
        $btn.prop("disabled", true);

        deleteMatch(userId)
          .then((response) => {
            if (response.code === 200) {
              alert("删除成功");
              loadTableData();
            } else {
              alert("删除失败: " + (response.message || "未知错误"));
            }
          })
          .catch((error) => {
            console.error("删除用户失败:", error);
            alert("删除用户失败");
          })
          .finally(() => {
            $btn.html('<i class="fas fa-trash"></i>');
            $btn.prop("disabled", false);
          });
      }
    });

    // 保存用户表单
    $("#save-btn").on("click", function () {
      const $form = $("#modal-form");
      const userId = $("#modal-form-id").val();

      if (!$form[0].checkValidity()) {
        $form[0].reportValidity();
        return;
      }

      const userData = {
        id: userId || null,
        firstTeamId: $("#modal-form-first-team-id").val() || null,
        secondTeamId: $("#modal-form-second-team-id").val() || null,
        matchName: $("#modal-form-match-name").val(),
        matchTime: $("#modal-form-match-time").val(),
      };



      const $btn = $(this);
      $btn.html(
        '<span class="spinner-border spinner-border-sm"></span> 保存中...'
      );
      $btn.prop("disabled", true);

      const request = userId ? updateMatch(userData) : addMatch(userData);

      request
        .then((response) => {
          if (response.code === 200) {
            alert(userId ? "用户信息已更新" : "用户添加成功");
            $("#modal").modal("hide");
            loadTableData();
          } else {
            alert(
              (userId ? "更新" : "添加") +
                "用户失败: " +
                (response.message || "未知错误")
            );
          }
        })
        .catch((error) => {
          console.error("保存用户失败:", error);
          alert("保存用户失败");
        })
        .finally(() => {
          $btn.html("保存");
          $btn.prop("disabled", false);
        });
    });
  }
});
